﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using EzDesk.Core.Interface;
using EzDesk.Utility.Log;
using EzDesk.Core.Model;

namespace EzDesk.Core.ServiceImpl.Services
{
    public class WebOperationProperties : IOperationProperties
    {
        EzDeskUserAgentType _userAgent;
        public WebOperationProperties()
        {
            _userAgent = getCurrentUserAgent();
        }

        private EzDeskUserAgentType getCurrentUserAgent()
        {
            string userAgentStr = null;
            userAgentStr = getUserAgentString().ToUpper();

            //todo: 以后删除
            if (string.IsNullOrEmpty(userAgentStr))
            {
                return EzDeskUserAgentType.DesktopClient;
            }

            if (!userAgentStr.Contains("EZDESK"))
            {
                LogEx.TRACE("CoreClientService", "错误的useragent字符串" + userAgentStr);
                throw new Exception("非法的userAgent字符串");
            }

            var userAgent = EzDeskUserAgentType.GenericMobile;
            if (userAgentStr.Contains("GENERICMOBILE"))
            {
                userAgent = EzDeskUserAgentType.GenericMobile;
            }
            if (userAgentStr.Contains("DESKTOPCLIENT"))
            {
                userAgent = EzDeskUserAgentType.DesktopClient;
            }

            return userAgent;
        }

        private string getUserAgentString()
        {
            string userAgentStr = "";

            HttpRequestMessageProperty httpRequestProperty = null;
            object propertyValue = null;

            if (OperationContext.Current.IncomingMessageProperties.TryGetValue(
                HttpRequestMessageProperty.Name,
                out propertyValue
                ))
            {
                httpRequestProperty = (HttpRequestMessageProperty)propertyValue;
                var headers = httpRequestProperty.Headers;
                userAgentStr = headers["User-Agent"];
            }
            if (string.IsNullOrEmpty(userAgentStr))
            {
                userAgentStr = "";
            }
            return userAgentStr;
        }

        public EzDeskUserAgentType UserAgent
        {
            get { return _userAgent; }
        }
    }
}
